package com.alibaba.boot.netty.netty;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.CharsetUtil;

import java.nio.charset.StandardCharsets;

//自定义一个handler 需要继承netty规定好的某个handlerAdapter
//自定义的handler 才能称为handler
public class NettyServerHandler extends ChannelInboundHandlerAdapter {


    public volatile   static Channel clientChannel;


    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("channel active write chnnel instance in filed");
        clientChannel = ctx.channel();
    }

    /**
     * @param ctx 上下文对象，含有管道 pipline,通道chnnel,地址
     * @param msg
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        System.out.println("server ctx=" +ctx);
        ByteBuf buf = (ByteBuf) msg;
        System.out.println("client send:"+buf.toString());
        System.out.println("client address:"+ctx.channel().remoteAddress());

    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.writeAndFlush(Unpooled.copiedBuffer("hello this is server".getBytes(StandardCharsets.UTF_8)));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println(cause);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        clientChannel = null;
    }



    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
       if (evt instanceof IdleStateEvent){

           IdleStateEvent event = (IdleStateEvent) evt;


           switch (event.state()){
               case READER_IDLE:
                   System.out.println("read tiread");
                   break;
               case WRITER_IDLE:
                   System.out.println("write tired");
                   break;
               case  ALL_IDLE:
                   System.out.println("all tired");
                   break;
           }
           System.out.println();

       }
    }
}
